package com.hope.service.impl;

import com.hope.domain.dto.CartDTO;
import com.hope.domain.pojo.Cart;
import com.hope.domain.pojo.Result;
import com.hope.mapper.CartMapper;
import com.hope.service.CartService;
import com.hope.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    public CartMapper cartMapper;

    @Override
    public Result createCart(Cart cart) {
        Long userId=Long.parseLong(ThreadLocalUtil.get());
        cart.setUserId(userId);
        int row = cartMapper.createCart(cart);
        if (row == 0) {
            log.error("cart:{}", cart);
            return Result.fail("购物车] 加购请求 有问题,发生了点事故");
        }
        log.info("购物车] 加购请求 cart={}", cart);
        return Result.ok(cart);
    }

    @Override
    public Result deleteCart(Long id) {
        log.info("[购物车] 删除请求, id: {}", id);
        int row = cartMapper.deleteCart(id);
        return row > 0 ? Result.ok("删除成功") : Result.fail("删除失败");
    }

    @Override
    public Result getCart(Long id) {
        log.info("[购物车] 单条查询, id: {}", id);
        Cart cart = cartMapper.getCart(id);
        return cart != null ? Result.ok(cart) : Result.fail("未找到购物车记录");
    }

    @Override
    public Result getCartList() {
        String oid = ThreadLocalUtil.get();
        if(oid==null){
            return Result.ok(List.of());
        }
        Long userId=Long.parseLong(oid);
        List<CartDTO> cartList = cartMapper.getCartList(userId);

        log.info("cartList:{}", cartList);
        return Result.ok(cartList);
    }

    @Override
    public Result updateCart(Cart cart) {
        log.info("[购物车] 更新请求: {}", cart);
        String oid = ThreadLocalUtil.get();
        if(oid==null){
            return Result.ok(List.of());
        }
        Long userId=Long.parseLong(oid);
        cart.setUserId(userId);
        int row = cartMapper.updateCart(cart);

        return row > 0 ? Result.ok("更新成功") : Result.fail("更新失败");
    }

    @Override
    public Result deleteALLCart(Long id) {
        log.info("[购物车] 删除请求, user_id: {}", id);
        int row = cartMapper.deleteALLCart(id);
        return row > 0 ? Result.ok("删除成功") : Result.fail("删除失败");
    }
}
